import { useEffect, useRef, useState } from 'react';
import genCustomFilter from './lib/genCustomFilter';
import _ from 'lodash';


function adapterLegacy(data) {
    return 'filterProps' in data && data.filterProps ? { ...data } : { ...data, filterProps: data };
}

function useGenColumns(originColumns, { filterDropdownMap={}, tableState, columnSet, resizable }) {
    const [ columns, setColumns ] = useState([]); 
    //和缓存比较新增的列
    const addedColumns = useRef([]);
    //和缓存比较删除的列
    const removedColumns = useRef([]);
    const columnsRef = useRef([]);
    
    const {getCachedByKey, cacheKey} = columnSet || {};
    const cachedColumns = getCachedByKey && getCachedByKey(cacheKey);

    useEffect(() => {
        columnsRef.current = columns;
    }, [columns]);

    useEffect(() => {
        if(_.isEmpty(originColumns)) return;
        let _columns = [];
        let resultColumns = cachedColumns? compareColumns(cachedColumns, originColumns): originColumns.filter(item => item.checked !== false);
        _columns = addColumnExtraInfo(resultColumns);
        setColumns(_columns);
    }, [originColumns, tableState.current.filters]);

    //cachedColumns和originColumns做比较
    const compareColumns = (cachedColumns, originColumns) => {
        let resultColumns = [],
            ignoredColumns = [];
        //先清空删除新增列 不然多次执行会有重复列
        addedColumns.current = [];
        removedColumns.current = [];
        
        //找到新增的列
        _.forEach(originColumns, (col) => {
            const targetCol = _.find(cachedColumns, {key: col.key});
            if(col.ignored) {
                ignoredColumns.push({...col});
            } else if(!targetCol) {
                //cachedColumns中没有并且不是ignored的列   
                resultColumns.push({ ...col });
                addedColumns.current.push({ ...col })
            } 
        })

        
        _.forEach(cachedColumns, (col) => {
            //originColumns里面删除的列就不展示
            const targetCol = _.find(originColumns, {key: col.key});
            if(targetCol && col.checked) {
                resultColumns.push({ ...targetCol })
            } else if(!targetCol){
                //找到删除的列
                removedColumns.current.push({ ...col});
            }
        })
        
        //把ignored的列加到最后
        resultColumns.push(...ignoredColumns);

        return resultColumns;
    }

    const addColumnExtraInfo = (columns) => {
        const result = [];
        const sorter = tableState.current?.sorter;
        const filters = tableState.current?.filters;
        columns.forEach((col, index) => {
            let extraColumnInfo = {} ;
            if ('filterOption' in col && col.filterOption) {
                /**
                 * * 自定义筛选组件
                 * * 从Filters中匹配筛选条件                 
                */
                let Filter = filterDropdownMap[col.filterOption.type];
                if (Filter) {
                   // let filterProps = adapterLegacy(col.filterOption).filterProps;
                   extraColumnInfo.filterDropdown = genCustomFilter(Filter, {...col, visible: true});
                }
                extraColumnInfo.filteredValue = filters && filters[col.key];
            }

            if(sorter && col.dataIndex === sorter.field) {
                extraColumnInfo.sortOrder = sorter.order;
            } else {
                extraColumnInfo.sortOrder = null;
            }

            if(resizable) {
                extraColumnInfo.onHeaderCell = column => ({
                    width: column.width,
                    onResize: handleResize(index)
                })
            }

            result.push({ ...col, ...extraColumnInfo });
        })
        return result;
    }

    const updateColumnsDisplay = (cachedColumns) => {
        setColumns(compareColumns(cachedColumns, originColumns));
    }

    const handleResize = index => (e, { size }) => {
        //!这里只能用columnsRef拿到最新的columns 如果直接用state里面的columns 因为handleResize首次渲染就调用了 后续每次渲染handleResize不用重新调用  
        //!所以antd table里面的handleResize实例永远是第一次创建的实例 handleResize闭包里面拿到的state里面的columns永远是初始的空数组
        const nextColumns = [...columnsRef.current];
        const column =  nextColumns[index];
        //最小宽度默认100
        const minWidth = column.minWidth || 100;
        nextColumns[index] = {
          ...column,
          width: size.width < minWidth? minWidth: size.width,
        };
        setColumns(nextColumns);
        if(resizable?.saveWidth) {
            saveColumnsWidth(nextColumns);
        }
    };

    /* 保存调整后的列宽 */
    const saveColumnsWidth = _.debounce((columns) => {
        const { saveWidth } = resizable;
        if (saveWidth && typeof saveWidth === 'function') {
            saveWidth(columns);
        }
    }, 1000)
    return { columns, originColumns, addedColumns, removedColumns, updateColumnsDisplay };
}
export default useGenColumns;